package com.waylau.netty.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author ZZZ
 * @version 1.0
 * @date 2019/3/13 0013
 */
public class BeanUtil {

    private BeanUtil() {
    }

    /**
     * @desc 深拷贝
     * @author ZZZ
     * @date 2019/3/13 0013
     * @version 1.0
     */
    public static Object deepCopy(Object source) {
        Class<?>[] interfaces = source.getClass().getInterfaces();
        boolean serialFlag = false;
        for (Class<?> anInterface : interfaces) {
            if (anInterface instanceof Serializable) {
                serialFlag = true;
            }
        }
        if(!serialFlag) {
            throw new RuntimeException("source must implements Serializable");
        }
        ByteArrayInputStream byteArrayInputStream = null;
        ObjectInputStream objectInputStream = null;
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)
        ) {
            objectOutputStream.writeObject(source);
            byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            return objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayInputStream.close();
                objectInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
